const { app, BrowserWindow, ipcMain, session, dialog } = require('electron')
const path = require('path')
const fs = require('fs');
const { autoUpdater } = require('electron-updater');

const isDev = process.env.NODE_ENV === 'development'

const GITEE_USER = 'lihoachen'
const GITEE_REPO = 'xiaolu-line-ai'
autoUpdater.setFeedURL({
    provider: 'generic',
    url: `https://gitee.com/${GITEE_USER}/${GITEE_REPO}/releases/download/latest/`
})

let mainWindow
let isUpdaterRunning = false;
let cachedToken = '';


// 缓存清理逻辑
function clearUpdateCache() {
    try {
        const userDataPath = app.getPath('userData');
        const localAppDataPath = process.env.LOCALAPPDATA ||
            path.join(app.getPath('appData'), '..', 'Local');
        const cachePaths = [
            path.join(userDataPath, 'update-cache'),
            path.join(userDataPath, 'xlx-updater'),
            path.join(userDataPath, 'xlx-Updater'),
            path.join(userDataPath, 'Electron', 'update-cache'),
            path.join(app.getPath('temp'), 'electron-updater'),
            path.join(app.getPath('appData'), 'xlx-updater'),
            path.join(localAppDataPath, 'xlx-updater')
        ];

        let clearedAny = false;

        cachePaths.forEach(cachePath => {
            const resolvedPath = path.resolve(cachePath);
            if (fs.existsSync(resolvedPath)) {
                try {
                    fs.rmSync(resolvedPath, {
                        recursive: true,
                        force: true,
                        maxRetries: 5,
                        retryDelay: 1000
                    });
                    console.log('✅ 强制清理缓存目录:', resolvedPath);
                    clearedAny = true;
                } catch (dirError) {
                    console.error('❌ 清理缓存失败:', resolvedPath, '原因:', dirError.message);
                }
            }
        });

        if (!clearedAny) {
            console.log('ℹ️ 未找到可清理的更新缓存目录');
        }
        return true;
    } catch (error) {
        console.error('❌ 全局缓存清理异常:', error.message);
        return false;
    }
}

function forceClearCache() {
    if (isUpdaterRunning) {
        console.warn('⚠️ 检测到更新进程正在运行，将先终止再清理');
        mainWindow?.webContents.send('update-message', {
            event: 'info',
            info: { message: '正在终止当前更新进程以清理缓存...' }
        });
        isUpdaterRunning = false;
    }

    const clearSuccess = clearUpdateCache();
    if (!clearSuccess) {
        mainWindow?.webContents.send('update-message', {
            event: 'error',
            error: {
                message: '自动清理缓存失败，请手动删除目录后重启',
                manualPath: path.resolve(process.env.LOCALAPPDATA || '', 'xlx-updater')
            }
        });
    }
    return clearSuccess;
}


// 窗口创建
function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1440,
        height: 810,
        minWidth: 1000,
        minHeight: 700,
        frame: false,
        titleBarStyle: 'hidden',
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            nodeIntegration: false,
            sandbox: false
        },
        icon: path.join(__dirname, '../build/icon.ico'),
        show: false
    })

    // 更新逻辑配置
    autoUpdater.autoDownload = false;
    autoUpdater.autoInstallOnAppQuit = true;
    autoUpdater.allowDowngrade = false;

    if (isDev) {
        autoUpdater.allowPrerelease = true;
    }

    // 监听updater状态变化
    autoUpdater.on('checking-for-update', () => {
        isUpdaterRunning = true;
        console.log('🔍 正在检查更新...');
        mainWindow.webContents.send('update-message', { event: 'checking-for-update' });
    });
    autoUpdater.on('update-available', (info) => {
        isUpdaterRunning = true;
        console.log('📢 发现更新:', info.version);
        mainWindow.webContents.send('update-message', {
            event: 'update-available',
            info: {
                version: info.version,
                releaseDate: info.releaseDate,
                releaseNotes: info.releaseNotes
            }
        });
    });
    autoUpdater.on('update-not-available', (info) => {
        isUpdaterRunning = false;
        console.log('✅ 无可用更新');
        mainWindow.webContents.send('update-message', {
            event: 'update-not-available',
            info: {
                version: info?.version || '当前版本',
                releaseDate: info?.releaseDate
            }
        });
    });
    autoUpdater.on('error', (err) => {
        isUpdaterRunning = false;
        console.error('❌ 更新错误:', err.message);
        mainWindow.webContents.send('update-message', {
            event: 'error',
            error: {
                message: err.message || '更新失败，请检查网络或稍后重试',
                stack: err.stack
            }
        });
    });
    autoUpdater.on('download-progress', (progressObj) => {
        console.log(`📥 下载进度: ${progressObj.percent.toFixed(1)}%`);
        mainWindow.webContents.send('update-message', {
            event: 'download-progress',
            progress: {
                percent: progressObj.percent,
                bytesPerSecond: progressObj.bytesPerSecond,
                transferred: progressObj.transferred,
                total: progressObj.total
            }
        });
    });
    autoUpdater.on('update-downloaded', (info) => {
        isUpdaterRunning = false;
        console.log('✅ 更新已下载完成:', info.version);
        mainWindow.webContents.send('update-message', {
            event: 'update-downloaded',
            info: {
                version: info.version,
                releaseDate: info.releaseDate,
                releaseNotes: info.releaseNotes
            }
        });
    });

    // 更新相关IPC
    ipcMain.on('start-download-update', async () => {
        console.log('📥 准备下载：先强制清理缓存');
        const clearSuccess = forceClearCache();

        if (!clearSuccess) {
            mainWindow.webContents.send('update-message', {
                event: 'error',
                error: { message: '缓存清理失败，无法启动下载' }
            });
            return;
        }

        try {
            await autoUpdater.downloadUpdate();
            console.log('📥 开始下载更新');
        } catch (error) {
            console.error('❌ 下载失败:', error.message);
            mainWindow.webContents.send('update-message', {
                event: 'error',
                error: { message: error.message || '下载更新失败' }
            });
        }
    });

    ipcMain.on('check-for-update-trigger', () => {
        autoUpdater.checkForUpdates().then(result => {
            console.log('🔍 更新检查结果:', result);
            if (result && result.updateInfo && result.updateInfo.version) {
                console.log('📢 可用更新版本:', result.updateInfo.version);
            } else {
                mainWindow.webContents.send('update-message', {
                    event: 'update-not-available',
                    info: { version: '当前已是最新版本' }
                });
            }
        }).catch(error => {
            isUpdaterRunning = false;
            console.error('❌ 检查更新失败:', error.message);
            mainWindow.webContents.send('update-message', {
                event: 'error',
                error: { message: error.message || '检查更新失败' }
            });
        })
    });

    ipcMain.on('quit-and-install-update', () => {
        autoUpdater.quitAndInstall()
    })

    ipcMain.on('clean-update-cache', () => {
        const success = forceClearCache();
        if (success) {
            mainWindow.webContents.send('update-message', {
                event: 'info',
                info: { message: '更新缓存已清理完成' }
            });
        }
    });

    // 应用加载
    if (isDev) {
        mainWindow.loadURL('http://localhost:5173')
        mainWindow.webContents.openDevTools()
    } else {
        const rootPath = app.getAppPath();
        const indexPath = path.join(rootPath, 'dist', 'index.html');

        const logPath = path.join(app.getPath('userData'), 'load-log.txt');
        fs.writeFileSync(logPath, `根路径: ${rootPath}\nHTML路径: ${indexPath}\n是否存在: ${fs.existsSync(indexPath)}`);

        mainWindow.loadFile(indexPath);
    }

    mainWindow.once('ready-to-show', () => {
        mainWindow.show()
        if (isDev) {
            mainWindow.webContents.on('devtools-opened', () => {
                mainWindow.focus()
                setImmediate(() => mainWindow.focus())
            })
        }
    })

    mainWindow.on('closed', () => {
        mainWindow = null
    })

    mainWindow.on('maximize', () => {
        mainWindow.webContents.send('window-maximized')
    })
    mainWindow.on('unmaximize', () => {
        mainWindow.webContents.send('window-unmaximized')
    })
}


// 关键修复：添加WebSocket请求拦截器，自动添加Authorization头
function setupWebSocketAuthInterceptor() {
    session.defaultSession.webRequest.onBeforeSendHeaders(
        { urls: ['ws://39.100.95.39:6001/websocket/*'] },
        (details, callback) => {
            try {
                details.requestHeaders['Authorization'] = cachedToken || '未获取到token';

                callback({ requestHeaders: details.requestHeaders });
            } catch (error) {
                console.error('❌ 添加WebSocket请求头失败:', error);
                callback({ requestHeaders: details.requestHeaders });
            }
        }
    );

    // 监听响应
    session.defaultSession.webRequest.onHeadersReceived(
        { urls: ['ws://39.100.95.39:6001/websocket/*'] },
        (details, callback) => {
            callback({ responseHeaders: details.responseHeaders });
        }
    );
}


// 接收渲染进程传递的token（发送更新通知）
ipcMain.on('set-auth-token', (event, token) => {
    if (token) {
        cachedToken = token;
        if (mainWindow) {
            mainWindow.webContents.send('token-updated', true);
        }
    } else {
        console.warn('\n⚠️ 主进程：收到空token');
        cachedToken = '';
    }
});


// 应用生命周期
app.whenReady().then(() => {
    setupWebSocketAuthInterceptor();

    setTimeout(() => forceClearCache(), 1000);
    createWindow()

    if (!isDev) {
        setTimeout(() => {
            autoUpdater.checkForUpdates().catch(error => {
                isUpdaterRunning = false;
                console.error('❌ 初始检查更新失败:', error.message);
                if (isDev) {
                    mainWindow?.webContents.send('update-message', {
                        event: 'error',
                        error: { message: error.message || '初始检查更新失败' }
                    });
                }
            });
        }, 3000);
    } else {
        setTimeout(() => {
            autoUpdater.checkForUpdates().catch(error => {
                isUpdaterRunning = false;
                console.error('❌ 开发环境检查更新失败:', error.message);
            });
        }, 3000);
    }
})

app.on('before-quit', () => {
    forceClearCache();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})


// 窗口控制IPC
ipcMain.on('minimize-window', () => {
    const window = BrowserWindow.getFocusedWindow()
    window?.minimize()
})

ipcMain.on('maximize-window', () => {
    const window = BrowserWindow.getFocusedWindow()
    if (window) {
        window.isMaximized() ? window.unmaximize() : window.maximize()
    }
})

ipcMain.on('close-window', () => {
    const window = BrowserWindow.getFocusedWindow()
    window?.close()
})

ipcMain.on('is-maximized', (event) => {
    const window = BrowserWindow.getFocusedWindow()
    event.returnValue = window ? window.isMaximized() : false
})

ipcMain.on('start-drag', (event) => {
    const window = BrowserWindow.fromWebContents(event.sender)
    if (window?.isMaximized()) {
        window.unmaximize()
        window.webContents.send('window-unmaximized')
    }
})


// 文件对话框与外部链接
ipcMain.handle('show-save-dialog', async (event, options) => {
    return await dialog.showSaveDialog(options)
})

ipcMain.on('show-item-in-folder', (event, filePath) => {
    shell.showItemInFolder(filePath)
})

ipcMain.on('open-external-window', (event, url) => {
    const win = new BrowserWindow({
        width: 1200,
        height: 800,
        autoHideMenuBar: true,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            sandbox: true
        },
        show: false
    })

    if (url?.startsWith('http')) {
        win.loadURL(url)
    } else {
        win.loadURL('about:blank')
    }

    win.once('ready-to-show', () => win.show())
    win.on('closed', () => win.destroy())
})


// 开发环境配置
if (isDev) {
    process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
}
